<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2024/6/6
 * Time: 13:09
 */

namespace app\common\cachemodel;

use app\common\model\BaseCache;
use XznsTools\cache\CacheManage;

class AppUserDeviceRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_user_device_record';
    protected $cacheModel = 'user.device_info';

    /**
     * 添加设备号信息
     * @param $data
     * @return int|string
     */
    public function saveData($data)
    {
        try
        {
            $id = $this->insertGetId($data);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $data['uid'])->rmCache();
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            $id = 0;
        }
        return $id;
    }

    /**
     * 添加设备号信息
     * @param $deviceId
     * @param $uid
     * @return bool
     */
    public function updateData($deviceId, $uid): bool
    {
        try
        {
            $this->where('uid', $uid)->update([
                'device_id' => $deviceId, 'update_time' => time()
            ]);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache();
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
        return true;
    }

    /**
     * 获取设备号信息
     * @param $uid
     * @param array $field
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function getUserDeviceInfo($uid, array $field = [])
    {

        return CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->getDataAndSet(function () use ($uid)
        {
            try
            {
                return $this->where(['uid' => $uid])->field('status,uid,create_time,device_id')->order('id desc')->findOrFail()->toArray();
            }
            catch (\Exception $e)
            {
                return [];
            }
        }, $field);
    }
}
